package com.weepal.pavement.mqtt.demo.job;

import com.weepal.pavement.mqtt.demo.service.DeviceFieldService;
import com.weepal.pavement.mqtt.demo.service.MqttDevicesService;
import com.weepal.pavement.mqtt.demo.vo.DeviceField;
import com.weepal.pavement.mqtt.demo.vo.MqttDevices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 主要为了添加需要监听的topic主题
 */
@Component
public class DefaultRunner implements ApplicationRunner {
    @Autowired
    private MqttPahoMessageDrivenChannelAdapter defaultAdapter;
    @Autowired
    private MqttDevicesService mqttDevicesService;
    @Autowired
    private DeviceFieldService deviceFieldService;

    // 用你自己的方式查询topic，这里作为demo这样写了（测试用）
//    private static String[] topics;
//
//    static {
//        topics = new String[2];
//        topics[0] = "face/response";
//        topics[1] = "mqtt/znkj/fabu05";
//    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //加载设备信息
        List<MqttDevices> devices = mqttDevicesService.getList(new HashMap<>(2));
        //加载所有设备的字段信息
        List<DeviceField> fields = deviceFieldService.getAll();
        matchField(devices, fields);
        MqttDevicesMap.setDevices(devices);

        //加载接收信息的主体（测试用）
//        defaultAdapter.addTopic(topics[0], 0);
//        defaultAdapter.addTopic(topics[1], 0);
        for (MqttDevices d : devices) {
            defaultAdapter.addTopic(d.getSubGateway(), 0);
        }
    }

    /**
     * 将解析字段放到设备内
     */
    public void matchField(List<MqttDevices> devices, List<DeviceField> fields) {
        for (MqttDevices device : devices) {
            ConcurrentHashMap<String, DeviceField> f = new ConcurrentHashMap<>();
            int index = 0;
            for (; index < fields.size(); index++) {
                DeviceField field = fields.get(index);
                if (field.getDeviceId().equals(device.getKid())) {
                    f.put(field.getJsonKey(), field);
                }
            }
            device.setFields(f);
        }
    }
}
